package com.wechatapp.mengyao.poetry.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @author yanghuaxu
 * @date 2025/5/27 9:54
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${spring.data.elasticsearch.rest.uris}")
    private String[] esHosts;

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 1. 创建低级客户端
        RestClient restClient = RestClient.builder(parseHosts())
                .setRequestConfigCallback(builder ->
                        builder.setConnectTimeout(5000).setSocketTimeout(60000))
                .build();

        // 2. 创建JSON映射器
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new JavaTimeModule())
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // 3. 构建传输层
        ElasticsearchTransport transport = new RestClientTransport(
                restClient,
                new JacksonJsonpMapper(objectMapper)
        );

        // 4. 实例化客户端
        return new ElasticsearchClient(transport);
    }

    private HttpHost[] parseHosts() {
        return Arrays.stream(esHosts)
                .map(host -> {
                    String[] parts = host.split(":");
                    return new HttpHost(parts[0], Integer.parseInt(parts[1]));
                })
                .toArray(HttpHost[]::new);
    }
}